package com.xjscrm.console.service.customer.childLogin.impl;

import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.MerchatChild;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.MapObjExchangeuUtils;
import com.xjscrm.console.biz.CaptchaService;
import com.xjscrm.console.common.util.TokenUitls;
import com.xjscrm.console.mapper.MerchatChildMapper;
import com.xjscrm.console.param.login.ChildLoginByPwdDto;
import com.xjscrm.console.service.customer.childLogin.ChildLoginService;
import com.xjscrm.console.vo.LoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ChildLoginServiceImpl implements ChildLoginService {

    private static Logger logger= LoggerFactory.getLogger(ChildLoginServiceImpl.class);

    @Autowired
    private TokenUitls tokenUitls;

    @Autowired
    private MerchatChildMapper merchatChildMapper;

    @Autowired
    private CaptchaService captchaService;
    @Override
    public Object childLoginByPwd(ChildLoginByPwdDto childLoginByPwdDto) {
        //增加滑块验证
        captchaService.authByCaptcha(childLoginByPwdDto.getNonceStr(),childLoginByPwdDto.getValue());
        //查询用户是否存在
        MerchatChild merchatChild = merchatChildMapper.getByAccount(childLoginByPwdDto.getUserAccount(), childLoginByPwdDto.getMerId());
        if (merchatChild==null){
            throw new BusinessException(ResponseCode.NOT_FOUND, ResponseMsg.LOGIN_ERROR);
        }
        if (merchatChild.getPassword().equals(childLoginByPwdDto.getPassword())){
            return getLoginVO(merchatChild);
        }else {
            //错误则返回错误信息
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.LOGIN_ERROR);
        }
    }

    private LoginVO getLoginVO(MerchatChild merchatChild) {
        LoginVO loginVO=new LoginVO();
        loginVO.setId(merchatChild.getId());
        loginVO.setMerId(merchatChild.getMerId());
        loginVO.setUserName(merchatChild.getUserName());
        loginVO.setUserAccount(merchatChild.getUserAccount());
        loginVO.setHeadImage(merchatChild.getHeadImage());
        loginVO.setType(1);

        //user对象转map
        Map<String,Object> map=new HashMap<>();
        Map userInfo = MapObjExchangeuUtils.objToMap(map, loginVO);
        //token,用户信息存入redis
        String accessToken = tokenUitls.generateToken(userInfo);
        String refreshToken = tokenUitls.generateRefreshToken();
        logger.info("accessToken is {},refreshToken is {}",accessToken,refreshToken);
        tokenUitls.saveTokenInfo(accessToken,userInfo,refreshToken);
        loginVO.setAuthToken(accessToken);
        loginVO.setRefreshToken(refreshToken);
        return loginVO;
    }
}
